// 定义🐍的类
// 引入🐍的身体
import SnakeBody from './SnakeBody';
import { direction } from '../type/type';
const dirMap=new Map([['ArrowUp',0],['ArrowDown',3],['ArrowLeft',1],['ArrowRight',2]]);
export default class Snake {
    // 表示🐍头的元素
    private snakeHead: SnakeBody;
    // 表示🐍身体的集合
    public snakeBody: SnakeBody[];
    // 表示🐍的容器
    private snake: HTMLElement = document.getElementById('snake')!;
    // 表示🐍的移动方向
    private direction: direction = 'ArrowUp';

    constructor() {
        // 获取🐍头
        const head = <HTMLElement>document.querySelector('#snake .snake-body')!;
        // 获取🐍的身体
        const body = [...document.getElementsByClassName('snake-body')];
        // 设置🐍头
        this.snakeHead = new SnakeBody(true, head);
        // 设置🐍的身体
        this.snakeBody = [];
        body.forEach((item) => {
            this.snakeBody.push(new SnakeBody(false, item as HTMLElement))
        })
    }

    // 获取🐍头的现在位置
    getSnakeHeadPosition(){
        return this.snakeHead.position;
    }

    // 获取蛇头的下一个位置
    getHeadNextPosition():[leftX: number, topY: number]   {
        const [leftX, topY] = this.snakeHead.position;
        switch (this.direction) {
            case 'ArrowUp':     // 向上移动,蛇头top值减少
                return [leftX, topY - 10];
            case 'ArrowDown':
                return [leftX, topY + 10];
            case 'ArrowLeft':
                return [leftX - 10, topY];
            case 'ArrowRight':
                return [leftX + 10, topY];
        }
    }

    // 开始移动
    // 接收一个参数，表示是否吃到了食物，要往尾巴上添加snakeBody
    // 返回值表示吃到食物了，通知控制器将willEat改为false
    snakeRun(willEat: boolean=false): void {
        const position=this.snakeBody.reduce((beforeValue, curItem, index, arr) => {
            const prevPosition = curItem.position;
            curItem.position = beforeValue;
            return prevPosition;
        }, this.getHeadNextPosition());
        if(willEat){
            console.log(position);
            this.addSnakeBody(position);
        }
    }

    // 添加🐍的身体
    addSnakeBody(position:[number, number]): void {
        const snakeBody = document.createElement("div");
        snakeBody.className = 'snake-body';
        const $snakeBody = new SnakeBody(false, snakeBody);
        $snakeBody.position=position;
        this.snakeBody.push($snakeBody);
        this.snake.appendChild(snakeBody);
    }

    // 修改移动方向
    changeDirection(direction:direction): boolean {
        let a = dirMap.get(direction)!
        let b = dirMap.get(this.direction)!
        if(a===b||a+b===3) return false;
        else {
            this.direction = direction;
            return true;
        }
    }

    // 重置🐍的身体和头的位置
    reset(){
        this.snakeBody.forEach((body, index) => {
            if(index === 0) return;
            body.removeBody();
        });
        this.snakeBody=[this.snakeHead];
        this.snakeHead.position=[150,150];
    }

    showSnake(msg:string){
        this.snake.style.display=msg;
    }
}